package com.senven.order.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.senven.common.entity.Order;
import com.senven.common.vo.CommonResult;
import com.senven.order.config.AliPayConfig;
import com.senven.order.mapper.OrderMapper;
import com.senven.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wt
 * @since 2022-08-31
 */
@RestController
@RequestMapping("/order/order")
public class OrderController {

    private static final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";

    @Autowired
    private IOrderService orderService;

    @Autowired
    private AliPayConfig aliPayConfig;

    @Autowired
    private OrderMapper orderMapper;

    //支付宝支付
    @RequestMapping("/alipay")
    public void alipay(String orders, HttpServletResponse httpResponse) throws IOException {

        System.out.println("orders=========>"+orders);
        //根据订单号查询订单信息
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("orders",orders);
        wrapper.eq("status",0);
        Order order = orderMapper.selectOne(wrapper);


        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(), aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        //根据订单编号,查询订单相关信息

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orders;
        //付款金额，必填
        String total_amount = order.getTotal();
        //订单名称，必填
        String subject = "外卖付款";
        //商品描述，可空
        String body = "";
        request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @PostMapping(value = "/returnUrl")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, aliPayConfig.getAlipayPublicKey(), CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号=" + out_trade_no);
            System.out.println("支付宝交易号=" + trade_no);
            System.out.println("付款金额=" + total_amount);

            //更新订单状态
            Order order = new Order();
            order.setStatus(1);
            order.setPlaceTime(LocalDateTime.now());
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("orders",out_trade_no);
            wrapper.eq("status",0);
            orderMapper.update(order,wrapper);

            return "ok";//跳转付款成功页面
        } else {
            return "no";//跳转付款失败页面
        }
    }


    //微信支付
    @PostMapping("/createNavite")
    public CommonResult createNavite(String orders){
        return orderService.createNavite(orders);
    }
    @PostMapping("/queryPayStutus")
    public CommonResult queryPayStutus( String orders){
        return orderService.queryPayStutus(orders);
    }

    //响应式--通过用户id查询该用户的所有订单
    @PostMapping("/findOrderByUserid")
    public CommonResult findOrderByUserid(String userid){
        String s = String.valueOf(userid);
        CommonResult result = orderService.findOrderByUserid(userid);
        return result;
    }

    //响应式----通过订单id查询订单涉及的商品
    @PostMapping("/findOrderByOrderId")
    public CommonResult findOrderByOrderId(String orderid){
        CommonResult result = orderService.findOrderByOrderId(orderid);
        return result;
    }

    //后台--查询所有订单
    @PostMapping("/backFindAllOrder")
    public CommonResult backFindAllOrder(Integer currentPage, Integer pageSize, @RequestBody Map map){
        System.out.println(currentPage);
        CommonResult result = orderService.backFindAllOrder(currentPage,pageSize,map);
        return result;
    }

    //后台---订单详情接口
    @PostMapping("/orderfindOrderByOrderId")
    public CommonResult orderFindOrderByOrderId(Integer currentPage, Integer pageSize, @RequestBody Map map){
        CommonResult result = orderService.orderFindOrderByOrderId(currentPage,pageSize,map);
        return result;
    }

    //确认发货
    @PostMapping("/confirmShipment")
    public CommonResult confirmShipment(@RequestBody Order order){
        System.out.println(order);
        CommonResult result = orderService.updateOrderStatus(order);
        return result;
    }
    //确认收货
    @PostMapping("/confirmRecepit")
    public CommonResult confirmRecipit(@RequestBody Order order){
        System.out.println(order);
        CommonResult result = orderService.updateOrderStatus(order);
        return result;
    }
}
